<script setup lang="ts">

import { reactive, ref } from 'vue';
import { postAction } from '@/service/request/action';
import { authMenuApi, viewRoleAuthApi } from '@/service/path/role';
import { StatusMessage } from '@/enum';

interface Props {
  menuList: Api.Auth.Menu[];
}
defineProps<Props>();
const formRef = ref();
const menuTreeRef = ref();
const state = reactive({
  isShowDialog: false,
  loading: false,
  loaded: false,
  menuIds: [],
  id: ''
});
const openDialog = (id: string) => {
  state.loaded = false;
  state.isShowDialog = true;
  state.id = id;
  postAction(viewRoleAuthApi, {id}).then(res => {
    if (!res.error) {
      state.loaded = true;
      state.menuIds = res.data;
    }
  });
};
const closeDialog = () => {
  state.isShowDialog = false;
};
const clickConfirm = () => {
  state.loading = true;
  postAction(authMenuApi, {
    menuIds: menuTreeRef.value.getCheckedData().keys,
    id: state.id
  }).then(res => {
    state.loading = false;
    if (!res.error) {
      window.$message?.success(StatusMessage.SUCCESS);
      closeDialog();
    }
  });
};
defineExpose({
  openDialog
});
</script>

<template>
  <n-modal v-model:show="state.isShowDialog" preset="dialog" title="分配角色"
           style="width: 600px;" :show-icon="false" :close-on-esc="false" :mask-closable="false">
    <n-scrollbar style="height: 200px;">
      <n-tree
        v-if="state.loaded"
        ref="menuTreeRef"
        block-line
        cascade
        checkable
        default-expand-all
        :selectable="false"
        label-field="title"
        key-field="id"
        :data="menuList"
        :default-checked-keys="state.menuIds"
      />
    </n-scrollbar>
    <template #action>
      <n-space justify="end">
        <n-button @click="closeDialog">取消</n-button>
        <n-button type="primary" @click="clickConfirm" :loading="state.loading">确定</n-button>
      </n-space>
    </template>
  </n-modal>
</template>

<style scoped>

</style>
